﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using asMeishi.web.Models;

namespace asMeishi.web.Controllers
{
    public class userController : Controller
    {
        DataSession<MongoDataContext, user> db = new DataSession<MongoDataContext, user>();
        [authorityFilter(actionEnum.manage, actionTypeEnum.str)]
        public ActionResult Index()
        {
            ViewData.Model = db.query;
            return View();
        }

        public ActionResult Detail(int id)
        {
            return View();
            //return Content("正在建设！");
        }

        public ActionResult Edit(string id)
        {
            ViewData.Model = db.GetById(id) ?? userC.createDefault();
            return View();
        }

        [HttpPost]
        public ActionResult Edit(string id, FormCollection collection)
        {
            user user = db.GetById(id);
            //id存储
            var oid = user.Id;
            TryUpdateModel(user);
            user.Id = oid;
            
            if (string.IsNullOrWhiteSpace(id) && dataChecking(d=>d.email==user.email))
            {
                TempData["info"] = "login_Name已经存在";
                return View(user);
            }

            try
            {
                db.Save(user);
                return RedirectToAction("Index");
            }
            catch (Exception e)
            {
                TempData["info"] = "保存错误：" + e.Message;
                return View(user);
            }
        }
        [authorityFilter(actionEnum.manage, actionTypeEnum.str)]
        public ActionResult Delete(string id)
        {
            ViewData.Model = db.GetById(id);
            return View();
        }

        //
        // POST: /user/Delete/5

        [HttpPost]
        [authorityFilter(actionEnum.manage, actionTypeEnum.str)]
        public ActionResult Delete(string id, FormCollection collection)
        {
            try
            {
                db.Delete(id);
                TempData["info"] = "删除成功！";
                return RedirectToAction("Index");
            }
            catch(Exception e)
            {
                TempData["info"] = "删除失败：" + e.Message;
                return View();
            }
        }

        private bool dataChecking(System.Linq.Expressions.Expression<Func<user, Boolean>> lambda)
        {
            return db.Where(lambda).Any();
        }

    }
}
